<script>
import { getMaxFloor } from "../../utils/tools";
export default {
  name: "customTable",
  props: {
    title: {
      type: String,
      default: '数据列表'
    },
    resParam: {
      type: String,
      default: "",
    },
    tableConfig: {
      type: Object,
      required: true,
    },
    column: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      columnSelect: {},
      resColumn: [],
      selectAll: true,
      realcolumn: [],
      indeterminate: false,
      defaultOption: {
        childrenDeep: 0,
        data: [],
        size: "mini",
        showRight: false,
        showPagination: true,
        height: 378, // 表格高度
        stripe: true, // 是否为斑马纹 table
        border: true, // 是否带有纵向边框
        fit: true, // 列宽度撑开,
        showHeader: true, // 显示表头
        rowKey: "id",
        useIndex: true, // 行索引
        useMultiSelect: true, // 是否多选
        useRadioSelect: true,
        highlightCurrentRow: true, //是否高亮当前行
        pageSize: 10,
        pageSizeList: [10, 20, 30, 40],
        layout: "total,prev,pager,next,sizes,jumper",
        total: 0,
        indent: 0,
        treeProps: {},
        actionColumns: [],
      },
    };
  },
  computed: {
    options() {
      return Object.assign({}, this.defaultOption, this.tableConfig);
    },
  },
  methods: {
    handleCheckAllChange(val) {
      this.indeterminate = false;
      for (var i in this.columnSelect) {
        this.columnSelect[i] = val;
      }
      this.visualColumn.forEach((column) => {
        column.show = val;
      });
    },
    handleCheckChange(val, item) {
      this.columnSelect[item] = val;
      this.indeterminate = !Object.values(this.columnSelect).every(
        (item) => item
      );
      this.selectAll = true;
      if (this.indeterminate) {
        const status = Object.values(this.columnSelect).every((item) => !item);
        this.indeterminate = !status;
        this.selectAll = false;
      }
      this.visualColumn.forEach((column) => {
        if (column.prop === item) {
          column.show = val;
        }
      });
      this.$forceUpdate();
      this.$refs.customTable.doLayout();
    },
    //单元格双击
    cellDblClick(row, column, cell, event) {
      this.$emit("cell-dblclick", row, column, cell, event);
    },
    //双击行
    rowDblClick(row, column, event) {
      this.$emit("row-dblclick", row, column, event);
    },
    //多选框状态改变
    checkBoxSelect(selection, row) {
      row = row ?? selection;
      this.$emit("checkBox-change", selection, row);
    },
    //每页展示条数改变
    sizechange(pageSize) {
      this.$emit("page-change", pageSize);
    },
    //当前页改变
    currentChange(current) {
      this.$emit("current-change", current);
    },
    renderTable() {
      let tableAllWidth = 0;
      const {
        useIndex,
        useMultiSelect,
        actionColumns,
        showPagination,
        showRight,
      } = this.options;
      if (document.getElementsByClassName("main")[0]) {
        const width =
          document.getElementsByClassName("main")[0].clientWidth - 20;
        this.realcolumn.forEach((item) => {
          tableAllWidth += item.show
            ? item.width
              ? Number(item.width)
              : 0
            : 0;
        });
        if (tableAllWidth < width) {
          const index = this.realcolumn.findLastIndex((item) => item.show);
          console.log(index);
          if (
            this.realcolumn[index].children &&
            this.realcolumn[index].children.length > 0
          ) {
            this.realcolumn[index].children.forEach((item) => {
              item.width = "";
            });
          } else {
            this.realcolumn[index].width = "";
          }
        }
        this.tableConfig.selectData?.forEach((item) => {
          this.$refs.customTable.toggleRowSelection(item, true);
        });
      } else {
      }
      const height = this.tableConfig.height ?? this.defaultOption.height;
      if (height) {
        this.options.height = getMaxFloor(this.realcolumn) * 37 + height;
      } else {
        delete this.options.height;
      }
      const directives = [
        {
          name: "drag",
        },
      ];
      return (
        <div>
          <el-card shadow="hover">
            {this.renderHeader()}
            <div style="display:flex;justify-content: space-between;align-items: center;margin-bottom:10px">
              {this.renderCustomTools()}
              {showRight && this.renderC()}
            </div>
            <el-table
              ref="customTable"
              data={this.options.data}
              column={this.resColumn}
              onCell-dblclick={this.cellDblClick}
              onRow-dblclick={this.rowDblClick}
              onSelect={this.checkBoxSelect}
              onSelect-all={this.checkBoxSelect}
              {...{ directives }}
              attrs={this.options}
            >
              {this.renderEmpty()}
              {useMultiSelect && this.renderSelect()}
              {useIndex && this.renderIndex()}
              {delete this.$scopedSlots.empty}
              {actionColumns.map((item) => {
                return this.renderActionColumns(item);
              })}
              {this.realcolumn.map((column, i) => {
                if (column.show) {
                  return (
                    <tableHeader
                      scopedSlots={this.$scopedSlots}
                      column={column}
                    />
                  );
                }
              })}
            </el-table>
            {showPagination && this.renderPagination()}
          </el-card>
        </div>
      );
    },
    xiala(data) {
      return data.map((item) => {
        if (item.children && item.children.length > 0) {
          return this.xiala(item.children);
        } else {
          return item;
        }
      });
    },
    renderC() {
      const arr = this.resColumn.map((item) => item);
      let num = Object.values(this.columnSelect).length;
      Object.values(this.columnSelect).forEach((item) => {
        !item && num--;
      });
      return (
        <div style="display:flex;justify-content:end;width:100%">
          <el-dropdown
            onVisible-change={(e) => {
              if (!e) {
                this.realcolumn = JSON.parse(JSON.stringify(this.visualColumn));
                this.$nextTick(() => {
                  setTimeout(() => {
                    const dom = this.$refs.customTable.$el;
                    const table = dom.getElementsByClassName(
                      "el-table__body-wrapper"
                    )[0];
                    if (table.clientWidth + 10 >= table.scrollWidth) {
                      this.$refs.customTable.$el.style.height =
                        this.options.height - 10 + "px";
                    } else {
                      this.$refs.customTable.$el.style.height =
                        this.options.height + "px";
                    }
                  }, 0);
                  this.$refs.customTable.doLayout();
                });
              }
            }}
            trigger="click"
            hide-on-click={false}
          >
            <i
              class="el-icon-s-unfold"
              style="font-size: 24px;cursor:pointer"
            />
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-checkbox
                  disabled={this.selectAll}
                  onChange={this.handleCheckAllChange}
                  indeterminate={this.indeterminate}
                  v-model={this.selectAll}
                  label="全选"
                >
                  全选
                </el-checkbox>
              </el-dropdown-item>
              {arr.map((item) => {
                return (
                  <el-dropdown-item>
                    <el-checkbox
                      disabled={num === 2 && this.columnSelect[item.prop]}
                      onChange={(e) => {
                        this.handleCheckChange(e, item.prop);
                      }}
                      v-model={this.columnSelect[item.prop]}
                    >
                      {item.label}
                    </el-checkbox>
                  </el-dropdown-item>
                );
              })}
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      );
    },
    renderHeader() {
      return (
        <div slot="header">
          {this.$slots.header ? (
            this.$slots.header
          ) : (
            <div style="display: flex;">
              <img src={require("./list.svg")} />
              <span style="color:#666;margin-left:10px;font-size:14px">
                {this.title}
              </span>
            </div>
          )}
        </div>
      );
    },
    renderCustomTools() {
      return this.$slots.customTools ? this.$slots.customTools : "";
    },
    renderEmpty() {
      return (
        <div slot="empty">
          {this.$slots.empty ? (
            this.$slots.empty
          ) : (
            <el-empty image-size={70}>
              <div style="height:20px;line-height: 20px;" slot="description">
                暂时没有数据哦
              </div>
            </el-empty>
          )}
        </div>
      );
    },
    //显示分页
    renderPagination() {
      const { pageSize, pageSizeList, layout, total } = this.options;
      return (
        <el-pagination
          style="margin-top:10px"
          onSize-change={this.sizechange}
          onCurrent-change={this.currentChange}
          layout={layout}
          pageSizes={pageSizeList}
          pageSize={pageSize}
          small
          background
          total={total}
        ></el-pagination>
      );
    },
    //右侧操作
    renderActionColumns(actionColumns) {
      const { width, label, slotName } = actionColumns;
      return (
        <el-table-column
          scopedSlots={{
            default: (scoped) => {
              return this.$scopedSlots[slotName](scoped);
            },
          }}
          fixed="right"
          label={label}
          width={width}
          align="center"
          resizable={false}
        />
      );
    },
    //添加索引
    renderIndex() {
      return (
        <el-table-column
          resizable={false}
          type="index"
          label="序号"
          width=""
          align="center"
        />
      );
    },
    //多选
    renderSelect() {
      return <el-table-column align="center" type="selection" width="" />;
    },
    // renderRadioSelect() {
    //   return (
    //     <tableHeader
    //       scopedSlots={this.$scopedSlots}
    //       column={{
    //         align: "center",
    //         width: "40",
    //         label: "",
    //         prop: "selectRadio",
    //       }}
    //     />
    //   );
    // },
    deepColumn(columns) {
      columns.forEach((item) => {
        item.show = true;
        item.width = item.width || "";
        if (item.children && item.children.length > 0) {
          this.deepColumn(item.children);
        }
      });
    },
  },
  render() {
    return this.renderTable();
  },
  activated() {
    this.$refs.customTable.doLayout();
  },

  mounted() {
    this.$nextTick(() => {
      const dom = this.$refs.customTable.$el;
      const table = dom.getElementsByClassName("el-table__body-wrapper")[0];
      if (table.clientWidth + 10 >= table.scrollWidth) {
        this.$refs.customTable.$el.style.height =
          this.options.height - 10 + "px";
      }
    });
  },
  created() {
    this.column.forEach((item) => (item.show = true));
    this.resColumn = JSON.parse(JSON.stringify(this.column));
    if (this.resParam) {
      // 采用后台数据做为表头
      this.resColumn = [];
    }
    const realcolumn = JSON.parse(JSON.stringify(this.resColumn));
    const realcolumn1 = JSON.parse(JSON.stringify(this.resColumn));
    this.visualColumn = realcolumn1;
    realcolumn1.forEach((item) => {
      this.columnSelect[item.prop] = true;
    });
    this.deepColumn(realcolumn);
    this.realcolumn = realcolumn;
  },
};
</script>

<style lang="less" scoped>
:deep(.el-card__header) {
  padding: 10px 20px;
  background-color: #fafafa;
}
</style>
